<?php
declare (strict_types=1);

namespace addons\BuilderPlus\driver;

use app\common\tool\Result;

class Version
{
    private string $name = 'BuilderPlus';

    private string $format = '.zip';

    private string $domain = 'http://erp.test.daenmende.com/';

    private string $slash = DIRECTORY_SEPARATOR;

    private string $api;

    private string $installPath;

    private string $staticPath;

    private string $download;

    public function __construct()
    {
        $this->api = $this->domain . 'index/addons/getBuilderPlus';
        $this->installPath = app()->getRootPath() . 'addons' . $this->slash . $this->name;
        $this->download = $this->domain . '/v4_addons/' . $this->name . $this->format;
        $this->staticPath = app()->getRootPath() . 'public' . $this->slash . 'static' . $this->slash . 'admin' . $this->slash . 'addons';
    }

    public function check()
    {
        $plugin = $this->getPlugin();

        if ($plugin['version'] > getBuilderConfig('version')) {
            return Result::success('发现新版本：' . $plugin['version']);
        } else {
            return Result::fail('已经是最新版本');
        }

    }

    public function update()
    {
        $plugin = $this->getPlugin();
        if ($plugin['version'] <= getBuilderConfig('version')) {
            return Result::fail('当前已是最新版本，无需更新');
        }

        file_put_contents($this->installPath . $this->format, file_get_contents($this->download));

        $package = [
            [
                'filename'    => $this->installPath . $this->format,
                'installPath' => $this->installPath,
            ],
            [
                'filename'    => $this->installPath . $this->slash . 'core.zip',
                'installPath' => $this->installPath . $this->slash,
            ],
            [
                'filename'    => $this->installPath . $this->slash . 'static.zip',
                'installPath' => $this->staticPath . $this->slash . lcfirst($this->name),
            ]
        ];

        $zip = new \ZipArchive;
        foreach ($package as $item) {
            if ($zip->open($item['filename']) === true) {
                $zip->extractTo($item['installPath']);
                $zip->close();
            } else {
                return Result::fail('文件解压失败，请稍后再试');
            }
            unlink($item['filename']);
        }

        //更新本地版本号
        setBuilderConfig(['version' => $plugin['version']]);

        return Result::success('更新成功');
    }


    public function getPlugin()
    {
        return json_decode(file_get_contents($this->api), true)['data'];
    }
}